<?php
/**
 * This is Cms model file. 
 *
 */
App::uses('LilAppModel', 'Lil.Model');
/**
 * Cms class
 *
 * @uses          LilAppModel
 * @package       LilCms
 * @subpackage    LilCms.Model
 */
class CmsMenu extends LilAppModel {
/**
 * name property
 *
 * @var string 'CmsMenu'
 */
	public $name = 'CmsMenu';
/**
 * actsAs property
 *
 * @var array '
 */
	public $actsAs = array('Tree');
	
	public $order = 'lft';
/**
 * generateTree method
 *
 * create array for Menu selection
 *
 * @param string $r
 * @param array $options
 * @return array Two different arrays; first for select element, second for tree with js
 */
	public function generateTree($r = 'both', $options = array()) {
		$defaults = array(
			'path_separator' => ' | ',
			'order'          => 'CmsMenu.lft',
			'recursive'      => -1
		);
		$options = array_merge($defaults, $options);
		
		$stack = array(); $p = array(); 
		$levels = array(); $path = array();
		
		$categories = $this->find('all', $options);
		
		foreach ($categories as $category) {
			while ($stack && ($stack[count($stack) - 1] < $category['CmsMenu']['rght'])) array_pop($stack);
			while (count($levels) > count($stack)) array_pop($levels);
			
			// set path
			$pro = array(
				'id'       => $category['CmsMenu']['id'],
				'caption'  => $category['CmsMenu']['caption'],
				'children' => array(),
				'level'    => count($stack)
			);
			
			$title_var = array();
			$current_var = &$path;
			foreach ($levels as $level) { 
				$title_var[] = $current_var[$level]['caption'];
				$current_var = &$current_var['children'];
			}
			
			$title_var[] = $pro['caption'];
			$current_var[$category['CmsMenu']['id']] = $pro;
			
		 	$levels[count($stack)] = $category['CmsMenu']['id'];
		 	
		 	$stack[] = $category['CmsMenu']['rght'];
			$p[$category['CmsMenu']['id']] = implode($options['path_separator'], Set::filter($title_var));
		}
		
		$ret = array('simple' => $p, 'threaded' => $path);
		if ($r == 'both' || !isset($ret[$r])) return $ret;
		else return $ret[$r];
	}
}